import { history } from '@umijs/max';
import { useCallback, useEffect, useState } from 'react';

// 标签页类型定义
export interface PageTab {
  key: string; // 完整的路由路径（包含 query 参数）
  pathname: string; // 路由路径（不含参数）
  title: string; // 标签标题
  closable: boolean; // 是否可关闭
  query?: string; // URL 查询参数
}

// 本地存储的 key
const STORAGE_KEY = 'page_tabs';
const MAX_TABS = 10; // 最大标签数量

// 不可关闭的路由列表
const NON_CLOSABLE_ROUTES = ['/workBench/collectorBench'];

export default () => {
  // 从 localStorage 恢复标签
  const getInitialTabs = (): PageTab[] => {
    try {
      const saved = localStorage.getItem(STORAGE_KEY);
      if (saved) {
        const tabs = JSON.parse(saved);
        // 确保至少有催收员工作台
        if (tabs.length === 0) {
          return [{ key: '/workBench/collectorBench', pathname: '/workBench/collectorBench', title: '催收员工作台', closable: false }];
        }
        return tabs;
      }
    } catch (error) {
      console.error('恢复标签失败:', error);
    }
    return [{ key: '/workBench/collectorBench', pathname: '/workBench/collectorBench', title: '催收员工作台', closable: false }];
  };

  const [tabs, setTabs] = useState<PageTab[]>(getInitialTabs);
  const [activeKey, setActiveKey] = useState<string>('');

  // 保存到 localStorage
  const saveTabs = useCallback((tabList: PageTab[]) => {
    try {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(tabList));
    } catch (error) {
      console.error('保存标签失败:', error);
    }
  }, []);

  // 添加标签（支持 query 参数，让带参数的页面也能独立标签）
  const addTab = useCallback(
    (pathname: string, title: string, query?: string) => {
      setTabs((prevTabs) => {
        // 完整路径作为 key（pathname + query）
        const fullPath = query ? `${pathname}?${query}` : pathname;
        
        // 检查标签是否已存在
        const existingTab = prevTabs.find((tab) => tab.key === fullPath);
        if (existingTab) {
          return prevTabs;
        }

        // 检查是否超过最大数量，如果超过则删除最早的可关闭标签
        let newTabs = [...prevTabs];
        if (newTabs.length >= MAX_TABS) {
          const closableIndex = newTabs.findIndex((tab) => tab.closable);
          if (closableIndex !== -1) {
            newTabs.splice(closableIndex, 1);
          }
        }

        const newTab: PageTab = {
          key: fullPath,
          pathname,
          title,
          closable: !NON_CLOSABLE_ROUTES.includes(pathname),
          query,
        };

        newTabs = [...newTabs, newTab];
        saveTabs(newTabs);
        return newTabs;
      });
    },
    [saveTabs],
  );

  // 删除标签
  const removeTab = useCallback(
    (targetKey: string) => {
      setTabs((prevTabs) => {
        const targetIndex = prevTabs.findIndex((tab) => tab.key === targetKey);
        if (targetIndex === -1) return prevTabs;

        const newTabs = prevTabs.filter((tab) => tab.key !== targetKey);

        // 如果删除的是当前激活的标签，需要切换到相邻标签
        if (targetKey === activeKey) {
          let newActiveKey = '';
          if (newTabs.length > 0) {
            // 如果删除的不是最后一个，激活下一个，否则激活上一个
            if (targetIndex < prevTabs.length - 1) {
              newActiveKey = newTabs[targetIndex]?.key || newTabs[newTabs.length - 1].key;
            } else {
              newActiveKey = newTabs[targetIndex - 1]?.key || newTabs[0].key;
            }
          }
          if (newActiveKey) {
            history.push(newActiveKey);
          }
        }

        saveTabs(newTabs);
        return newTabs;
      });
    },
    [activeKey, saveTabs],
  );

  // 关闭其他标签
  const closeOtherTabs = useCallback(
    (targetKey: string) => {
      setTabs((prevTabs) => {
        const newTabs = prevTabs.filter((tab) => tab.key === targetKey || !tab.closable);
        saveTabs(newTabs);
        return newTabs;
      });
    },
    [saveTabs],
  );

  // 关闭所有可关闭的标签
  const closeAllTabs = useCallback(() => {
    setTabs((prevTabs) => {
      const newTabs = prevTabs.filter((tab) => !tab.closable);
      saveTabs(newTabs);
      // 跳转到第一个不可关闭的标签
      if (newTabs.length > 0) {
        history.push(newTabs[0].key);
      }
      return newTabs;
    });
  }, [saveTabs]);

  // 关闭右侧标签
  const closeRightTabs = useCallback(
    (targetKey: string) => {
      setTabs((prevTabs) => {
        const targetIndex = prevTabs.findIndex((tab) => tab.key === targetKey);
        if (targetIndex === -1) return prevTabs;

        const newTabs = prevTabs.filter((tab, index) => {
          if (index <= targetIndex) return true;
          return !tab.closable;
        });
        saveTabs(newTabs);
        return newTabs;
      });
    },
    [saveTabs],
  );

  // 刷新当前标签（重新加载页面）
  const refreshTab = useCallback((targetKey: string) => {
    // 通过重新 push 当前路由来刷新
    history.push(targetKey);
    window.location.reload();
  }, []);

  // 更新当前激活的标签
  const updateActiveKey = useCallback((key: string) => {
    setActiveKey(key);
  }, []);

  return {
    tabs,
    activeKey,
    addTab,
    removeTab,
    closeOtherTabs,
    closeAllTabs,
    closeRightTabs,
    refreshTab,
    updateActiveKey,
  };
};

